package com.kzw.oa.comm.web;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.kzw.core.model.OnlineUser;
import com.kzw.core.orm.Page;
import com.kzw.core.orm.PageRequest;
import com.kzw.core.orm.StringPropertyFilter;
import com.kzw.core.util.AppUtil;
import com.kzw.core.util.ExtjsUtil;
import com.kzw.core.util.StringUtil;
import com.kzw.core.web.action.BaseAction;
import com.kzw.oa.comm.model.Log;
import com.kzw.oa.comm.service.LogService;
import com.kzw.oa.util.JSON;

/**
 * @author kzwang
 */
@Controller
@Scope("prototype")
public class LogAction extends BaseAction {
	@Autowired
	private LogService logService;

	/**
	 * 显示列表
	 */
	public String list() {
		HttpServletRequest request = getRequest();
		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);
		
		if (ExtjsUtil.isExport(request)) { // 导出报表
			List<Log> resultList = logService.search(filters);
			request.setAttribute("__exportList", resultList);
			return SUCCESS;
		}
		
		Page<Log> page = logService.search2(pageRequest, filters);

		jsonString = new JSON(page).setDateFormater("yyyy-MM-dd HH:mm:ss").buildWithFilters(3);
		return SUCCESS;
	}

	/**
	 * 批量删除
	 */
	public String multiDel() {
		String[] ids = getRequest().getParameterValues("ids");
		logService.remove(ids);
		jsonString = "{success:true}";
		return SUCCESS;
	}	

	
	/**
	 * 导出选中记录数
	 * */
	public String exportSel() {
		HttpServletRequest request = getRequest();
		if (ExtjsUtil.isExport(request)) {
			String sids = request.getParameter("sids");
			List<Log> result = logService.getByIds(StringUtil.idStrToArr(sids, String.class));
			request.setAttribute("__exportList", result);
		}

		return SUCCESS;
	}

	/**
	 * 当前在线人数、今日访问量和总访问量
	 * */
	public String countIndex() {
		Map<String,OnlineUser> onlineUsers = AppUtil.getOnlineUsers();
		String hql = "select count(*) from SystemLog where exeOperation=?";
		Long totalCnt = logService.findUniqueByHQL(hql, "登陆系统");
		
		hql = "select count(*) from SystemLog where exeOperation=? and createtime between ? and ?";
		Calendar c1 = Calendar.getInstance();
		c1.set(Calendar.HOUR_OF_DAY, 0);
		c1.set(Calendar.MINUTE, 0);
		c1.set(Calendar.SECOND, 0);
		Date d1 = c1.getTime();
		
		c1.add(Calendar.DAY_OF_MONTH, 1);
		Date d2 = c1.getTime();
		Long todayCnt = logService.findUniqueByHQL(hql, "登陆系统", d1, d2);
		
		jsonString = "{onlineCnt: "+onlineUsers.size()+", totalCnt: "+totalCnt+", todayCnt: "+todayCnt+"}";
		return SUCCESS;
	}
	

}
